<?php
/**
 * Name: 上传组件控制器
 * User: 董坤鸿
 * Date: 2017/9/10
 * Time: 上午12:02
 */

namespace app\component\controller;

use think\Controller;
use think\Db;

class Upload extends Controller
{

    /**
     * 上传附件
     */
    public function uploader()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if ($info) {
            $data = [
                'name' => input('post.name'),
                'filename' => $info->getFilename(),
                'path' => 'uploads/' . $info->getSaveName(),
                'extension' => $info->getExtension(),
                'size' => $info->getSize(),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            Db::name('attachments')->insert($data);
            echo json_encode(['valid' => 1, 'message' => '/uploads/' . $info->getSaveName()]);
        } else {
            // 上传失败获取错误信息
            echo json_encode(['valid' => 0, 'message' => $file->getError()]);
        }

    }

    /**
     * 附件列表
     */
    public function filesLists()
    {
        $db = Db::name('attachments')->whereIn('extension', explode(',', strtolower(input("post.extensions"))))->order('id desc');
        $Res = $db->paginate(32);
        $data = [];
        if ($Res->toArray()) {
            foreach ($Res as $k => $v) {
                $data[$k]['created_at'] = $v['created_at'];
                $data[$k]['size'] = $v['size'];
                $data[$k]['url'] = '/' . $v['path'];
                $data[$k]['path'] = '/' . $v['path'];
                $data[$k]['name'] = $v['name'];
            }
        }
        echo json_encode(['data' => $data, 'page' => $Res->render() ?: '']);
    }

}